package com.tina.aspect;


import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.tina.entity.TiSystemLog;
import com.tina.entity.TiUsers;
import com.tina.mapper.TiSystemLogMapper;
import com.tina.util.IpUtils;
import com.tina.util.TimeUtitl;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一日志处理切面
 * <p>
 *
 * @author Tina
 * @Time-> 2020-6-10
 */
@Aspect
@Component
@Order(1)
public class TiSystemLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(TiSystemLogAspect.class);

    @Pointcut("execution(public * com.tina.controller.*.*(..))")
    public void systemLog() {
    }

    @Before("systemLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "systemLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Autowired
    private TiSystemLogMapper logMapper;

    @Around("systemLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        TiSystemLog systemLog = new TiSystemLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            systemLog.setLogDescription(apiOperation.value());
        }
        Subject subject = SecurityUtils.getSubject();
        TiUsers tiUsersSubject = (TiUsers) subject.getPrincipal();
        if (tiUsersSubject != null) {
            systemLog.setLogUserName(tiUsersSubject.getUserName());

        }
        systemLog.setLogIpaddr(IpUtils.getIpAddr(request));
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        systemLog.setLogBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        systemLog.setLogMethod(request.getMethod());

     //   systemLog.setLogParameter(getParameter(method, joinPoint.getArgs()));

        systemLog.setLogResult(JSONObject.toJSONString(result));
        systemLog.setLogSpendTime(Math.toIntExact(((int) (endTime - startTime))/1000));
        systemLog.setLogStartTime(TimeUtitl.dateTime());
        systemLog.setLogUri(request.getRequestURI());
        systemLog.setLogUrl(request.getRequestURL().toString());
        systemLog.setLogState(0);
     //   int insert = logMapper.insert(systemLog);
      //  LOGGER.info("insert={}", insert);
        LOGGER.info("{}", JSONUtil.parse(systemLog));
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
